$(function () {
    layui.use(['layer', 'table','formSelects','locals','form','util'],function(){
        var layer = layui.layer,
            table = layui.table,
            formSelects = layui.formSelects,
            form = layui.form,
            locals = layui.locals,
            util = layui.util;
        var theme = 'darkTheme';
        var areaId = null, areaArr = [];
        var pageName = getPageName();
        var localParam = locals.get(pageName); // 读取缓存的条件
        var grandTotalData = null;
        var devTypeObj = {
            1: {name: '水', unit:'T', img: 'meter-water.png'},
            0: {name: '电', unit:'kW·h', img: 'meter-electronic.png'},
            2: {name: '气', unit:'', img: 'meter-electronic.png'}
        };
        var devType = '0';
        var style = [
            { // 用水量柱体颜色
                color: {
                    x: 0, y: 1, x2: 1, y2: 1,
                    type: "linear",
                    global: false,
                    colorStops: [
                        {offset: 0, color: "rgba(54, 202, 208, .8)"},
                        {offset: 0.5, color: "rgba(54, 202, 208, .8)"},
                        {offset: 0.5, color: "rgba(36, 131, 176, .8)"},
                        {offset: 1, color: "rgba(36, 131, 176, .8)"}]
                }
            },{
                color: {
                    x: 0, y: 1, x2: 1, y2: 1,
                    type: "linear",
                    global: false,
                    colorStops: [{offset: 0, color: "rgba(153, 153, 153, .8)"},
                        {offset: 0.5, color: "rgba(153, 153, 153, .8)"},
                        {offset: 0.5, color: "rgba(105, 105, 105, .8)"},
                        {offset: 1, color: "rgba(105, 105, 105, .8)"}]
                }
            }];
        var toolTipObj = {
            timer1: null,
            timer2: null,
            timer3: null
        };
        var mychartsList = [];
        var allAreaList = [];
        var interval = 1000 * 60 * 10;  // 页面刷新频率 5min
        var pagetimer = null; // 页面定时器
        let counter = 0; // 已刷新次数

        // 监听水电表切换
        $('.devTypeCode-select .meter-btn').on('click',function () {
            devType = $(this).attr('deviceTypeCode');
            $('.devTypeCode-select .meter-btn').removeClass('btn-selected');
            $('.devTypeCode-select .meter-btn[deviceTypeCode="' + devType + '"]').addClass('btn-selected');
            for (let k in toolTipObj){
                clearInterval(toolTipObj[k]);
                toolTipObj[k] = null
            }
            for (let i = 0; i < mychartsList.length; i++) {
                mychartsList[i].clear();
            }
            locals.set(pageName, {area: areaArr, type: devType});
            localParam = {area: areaArr, type: devType};
            init();
        });

        init();

        function init() {
            if(localParam){
                devType = localParam.type;
            } else {
                devType = '0'
            }
            $('em.typeName').text(devTypeObj[devType].name);
            $('span.unit').text(devTypeObj[devType].unit);
            $('#devtype option[value="' + devType + '"]').prop('selected',true);
            if(devType == '1'){
                $('.water-wrap').removeClass('layui-hide');
                $('#electronic-animate').addClass('layui-hide');
            }else if(devType == '0'){
                $('.water-wrap').addClass('layui-hide');
                $('#electronic-animate').removeClass('layui-hide');
            }
            $('.devTypeCode-select .meter-btn').removeClass('btn-selected');
            $('.devTypeCode-select .meter-btn[deviceTypeCode="' + devType + '"]').addClass('btn-selected');
            // 今日用水
            bindTodalTotal();
            // 右上
            bindMonthOver();
            // 右下
            bindMonthTotal();
        }

        function bindTodalTotal() {
            $.ajax({
                type: "post",
                url: ctx + "/integrate/queryTodayByDevice.do",
                data: JSON.stringify({deviceTypeCode: devType}),
                contentType: "application/json",
                async: true,
                cache: false,
                dataType: "json",
                success: function (res) {
                    if (res.code == "000000") {
                        var data = res.data;

                        // 今日用量等数据
                        let topData = {
                            overCnt: data.overCnt,
                            totalCnt: data.totalCnt,
                            currentWater: data.currentWater, // decimalNum(data.currentWater),
                            standardWater: data.standardWater,
                            avg: data.avg , //decimalNum(data.avg),
                            avg1: data.avg1, // decimalNum(data.avg1),
                            rateCnt: data.standardExcessive == null? '0%' : data.standardExcessive,
                            monthStandardWater: data.monthStandardWater == null? 0 : data.monthStandardWater, // 月累计
                            monthStandardWater1: data.monthStandardWater1 == null? 0 : data.monthStandardWater1, // 总
                            mExcessiveWater: data.mExcessiveWater == null? '0%' : data.mExcessiveWater,
                            monthStandadElectricity: data.monthStandadElectricity == null? 0 : data.monthStandadElectricity, // 月累计
                            monthStandadElectricity1: data.monthStandadElectricity1 == null? 0 : data.monthStandadElectricity1, // 总
                            mExcessiveElectricity: data.mExcessiveElectricity == null? '0%' : data.mExcessiveElectricity
                        };
                        topCount(topData);

                        //本月累计用量 —— 区域select
                        renderAreaSel(data.areas);
                        allAreaList = data.areas;
                        //本月累计用量
                        grandTotalData = data.monitorMeters;
                        curMonthCount(areaArr, data.monitorMeters);

                        //当月用水总量
                        monthDaysTrendLine(data.monitorCurrentMonths);

                    } else {
                        layer.alert("系统异常，" + res.message);
                    }
                }, error: function (e) {
                    layer.alert("系统异常，请稍后再试");
                }
            });
        }

        // 顶部 —— 今日用水概况 + 综合能耗
        function topCount(data){
            $(".overCnt").text(data.overCnt);
            $(".totalCnt").text(data.totalCnt);
            $(".currentWater").text(data.currentWater);
            $(".avgCnt").text(data.avg);
            $(".avgCnt1").text(data.avg1);
            $(".standardWater").text(data.standardWater);
            $(".rateCnt").text(data.rateCnt);
            $(".month-rateCnt-water").text(data.mExcessiveWater);
            $(".month-standard-water").text(data.monthStandardWater); // 月累计
            $(".month-standard-water1").text(data.monthStandardWater1); // 月总
            $(".month-rateCnt-electric").text(data.mExcessiveElectricity);
            $(".month-standard-electric").text(data.monthStandadElectricity); // 月累计
            $(".month-standard-electric1").text(data.monthStandadElectricity1); // 月总

            rateColor(data.rateCnt, ".rateCnt");
            // 月累计节约率
            rateColor(data.mExcessiveWater, ".month-rateCnt-water");
            rateColor(data.mExcessiveElectricity, ".month-rateCnt-electric");
        }

        function rateColor(val, elm) {
            if(parseFloat(val) > 0){
                $(elm).addClass('fontGreen');
                $(".month-rateCnt-electric").removeClass('fontRed');
            }else if(parseFloat(val) < 0){
                $(elm).addClass('fontRed');
                $(elm).removeClass('fontGreen');
            }
        }

        //本月超标水表  图+表
        function bindMonthOver() {
            $.ajax({
                type: "post",
                url: ctx + "/integrate/getsuperMeter.do",
                data: JSON.stringify({deviceTypeCode: devType}),
                contentType: "application/json",
                async: true,
                cache: false,
                dataType: "json",
                success: function (res) {
                    if (res.code == "000000") {
                        var data = res.data;
                        // var data = {
                        //     totalCnt: 5,
                        //     overCnt: 0,
                        //     overList: [
                        //         {anotherName: '三楼-PTH-纯水AA',superWater: 60,superRate:'37.50%'},
                        //         {anotherName: '二楼-DES-自来水',superWater: 60,superRate:'37.50%'},
                        //         {anotherName: '四楼-PTH-纯水',superWater: 60,superRate:'37.50%'},
                        //         {anotherName: '四楼-化金-自来水',superWater: 60,superRate:'37.50%'},
                        //     ]
                        // };
                        var normalCnt = data.totalCnt - data.overCnt;
                        var overDataArray = [
                            { value:  normalCnt, name: '正常'},
                            { value: data.overCnt, name: '超标'}
                        ];

                        // 本月总量超标水表占比
                        // overCntPieChart(overDataArray,data.totalCnt);  // 2D
                        overCntPieChart3D(data.totalCnt,data.overCnt,normalCnt, data.overList); // 3D

                        // 超标水表表格
                        overCntTable(data.overList);
                    } else {
                        layer.alert("系统异常，" + res.message);
                    }
                }, error: function (e) {
                    layer.alert("系统异常，请稍后再试");
                }, complete: function () {
                    //layer.closeAll('loading');
                }
            });
        }

        // 现3D饼图
        function overCntPieChart3D(totalCnt,overCnt,normalCnt, overList) {
            /*************************
             pie3D 尝试
             更新时间: 2020.10.8 17:12 v1.1
             使用组件: grid3D、xAxis3D、yAxis3D、zAxis3D、surface
             EC 版本: 4.8.0
             GL 版本：0.4.3
             根据用户ZhXand618的模板克隆
             如果转载: 请注明出处
             *************************
             【 getParametricEquation 函数说明 】 :
             *************************
             根据传入的
             startRatio（浮点数）: 当前扇形起始比例，取值区间 [0, endRatio)
             endRatio（浮点数）: 当前扇形结束比例，取值区间 (startRatio, 1]
             isSelected（布尔值）:是否选中，效果参照二维饼图选中效果（单选）
             isHovered（布尔值）: 是否放大，效果接近二维饼图高亮（放大）效果（未能实现阴影）
             k（0~1之间的浮点数）：用于参数方程的一个参数，取值 0~1 之间，通过「内径/外径」的值换算而来。

             生成 3D 扇形环曲面
             *************************
             【 getPie3D 函数说明 】 :
             *************************
             根据传入的
             pieData（object）：饼图数据
             internalDiameterRatio（0~1之间的浮点数）：内径/外径的值（默认值 1/2），当该值等于 0 时，为普通饼图
             生成模拟 3D 饼图的配置项 option
             备注：饼图数据格式示意如下
             [{
                name: '数据1',
                value: 10
            }, {
                // 数据项名称
                name: '数据2',
                value : 56,
                itemStyle:{
                    // 透明度
                    opacity: 0.5,
                    // 扇形颜色
                    color: 'green'
                }
            }]

             *************************/

            // 生成扇形的曲面参数方程，用于 series-surface.parametricEquation
            function getParametricEquation(startRatio, endRatio, isSelected, isHovered, k, h) {

                // 计算
                let midRatio = (startRatio + endRatio) / 2;

                let startRadian = startRatio * Math.PI * 2;
                let endRadian = endRatio * Math.PI * 2;
                let midRadian = midRatio * Math.PI * 2;

                // 如果只有一个扇形，则不实现选中效果。
                if (startRatio === 0 && endRatio === 1) {
                    isSelected = false;
                }

                // 通过扇形内径/外径的值，换算出辅助参数 k（默认值 1/3）
                k = typeof k !== 'undefined' ? k : 1 / 3;

                // 计算选中效果分别在 x 轴、y 轴方向上的位移（未选中，则位移均为 0）
                let offsetX = isSelected ? Math.cos(midRadian) * 0.1 : 0;
                let offsetY = isSelected ? Math.sin(midRadian) * 0.1 : 0;

                // 计算高亮效果的放大比例（未高亮，则比例为 1）
                let hoverRate = isHovered ? 1.05 : 1;

                // 返回曲面参数方程
                return {

                    u: {
                        min: -Math.PI,
                        max: Math.PI * 3,
                        step: Math.PI / 32
                    },

                    v: {
                        min: 0,
                        max: Math.PI * 2,
                        step: Math.PI / 20
                    },

                    x: function(u, v) {
                        if (u < startRadian) {
                            return offsetX + Math.cos(startRadian) * (1 + Math.cos(v) * k) * hoverRate;
                        }
                        if (u > endRadian) {
                            return offsetX + Math.cos(endRadian) * (1 + Math.cos(v) * k) * hoverRate;
                        }
                        return offsetX + Math.cos(u) * (1 + Math.cos(v) * k) * hoverRate;
                    },

                    y: function(u, v) {
                        if (u < startRadian) {
                            return offsetY + Math.sin(startRadian) * (1 + Math.cos(v) * k) * hoverRate;
                        }
                        if (u > endRadian) {
                            return offsetY + Math.sin(endRadian) * (1 + Math.cos(v) * k) * hoverRate;
                        }
                        return offsetY + Math.sin(u) * (1 + Math.cos(v) * k) * hoverRate;
                    },

                    z: function(u, v) {
                        if (u < -Math.PI * 0.5) {
                            return Math.sin(u);
                        }
                        if (u > Math.PI * 2.5) {
                            return Math.sin(u) * h * .1;
                        }
                        return Math.sin(v) > 0 ? 1 * h * .1 : -1;
                    }
                };
            }

            // 生成模拟 3D 饼图的配置项
            function getPie3D(pieData, internalDiameterRatio) {
                let series = [];
                let sumValue = 0;
                let startValue = 0;
                let endValue = 0;
                let legendData = [];
                let k = typeof internalDiameterRatio !== 'undefined' ? (1 - internalDiameterRatio) / (1 + internalDiameterRatio) : 1 / 3;

                // 为每一个饼图数据，生成一个 series-surface 配置
                for (let i = 0; i < pieData.length; i++) {
                    sumValue += pieData[i].value;
                    let seriesItem = {
                        name: typeof pieData[i].name === 'undefined' ? `series${i}` : pieData[i].name,
                        type: 'surface',
                        parametric: true,
                        wireframe: {
                            show: false
                        },
                        pieData: pieData[i],
                        pieStatus: {
                            selected: false,
                            hovered: false,
                            k: k
                        }
                    };

                    if (typeof pieData[i].itemStyle != 'undefined') {
                        let itemStyle = {};
                        typeof pieData[i].itemStyle.color != 'undefined' ? itemStyle.color = pieData[i].itemStyle.color : null;
                        typeof pieData[i].itemStyle.opacity != 'undefined' ? itemStyle.opacity = pieData[i].itemStyle.opacity : null;

                        seriesItem.itemStyle = itemStyle;
                    }
                    series.push(seriesItem);
                }

                // 使用上一次遍历时，计算出的数据和 sumValue，调用 getParametricEquation 函数，
                // 向每个 series-surface 传入不同的参数方程 series-surface.parametricEquation，也就是实现每一个扇形。
                for (let i = 0; i < series.length; i++) {
                    endValue = startValue + series[i].pieData.value;
                    series[i].pieData.startRatio = startValue / sumValue;
                    series[i].pieData.endRatio = endValue / sumValue;
                    series[i].parametricEquation = getParametricEquation(series[i].pieData.startRatio, series[i].pieData.endRatio, false, false, k, series[i].pieData.value);
                    startValue = endValue;
                    legendData.push(series[i].name);
                }

                // 补充一个透明的圆环，用于支撑高亮功能的近似实现。
                series.push({
                    name: 'mouseoutSeries',
                    type: 'surface',
                    parametric: true,
                    wireframe: {
                        show: false
                    },
                    itemStyle: {
                        opacity: 0
                    },
                    parametricEquation: {
                        u: {
                            min: 0,
                            max: Math.PI * 2,
                            step: Math.PI / 20
                        },
                        v: {
                            min: 0,
                            max: Math.PI,
                            step: Math.PI / 20
                        },
                        x: function(u, v) {
                            return Math.sin(v) * Math.sin(u) + Math.sin(u);
                        },
                        y: function(u, v) {
                            return Math.sin(v) * Math.cos(u) + Math.cos(u);
                        },
                        z: function(u, v) {
                            return Math.cos(v) > 0 ? 0.1 : -0.1;
                        }
                    }
                });

                // 准备待返回的配置项，把准备好的 legendData、series 传入。
                let option = {
                    // animation: true,
                    title: {
                        text: '本月总量超标'+ devTypeObj[devType].name +'表占比',
                        x: 'center',
                        y: 10,
                        textStyle: {
                            fontSize: 18,
                            fontWeight: 'normal'
                        }
                    },
                    legend: {
                        data: legendData,
                        orient: 'vertical',
                        selectedMode: false,
                        top: 30,
                        right: 'center',
                        textStyle: {
                            color: '#fff',
                            fontSize: 12,
                            textAlign: 'left'
                        },
                        formatter: function(name) {
                            const num = name === '正常' ? normalCnt : overCnt;
                            let normalRate = 0;
                            let overRate = 0;
                            if(totalCnt > 0){
                                normalRate = normalCnt == 0 ? 0 : normalCnt / totalCnt * 100; // decimalNum(normalCnt / totalCnt * 100);
                                overRate = overCnt == 0 ? 0 : overCnt / totalCnt * 100; // decimalNum(overCnt / totalCnt * 100);
                            }
                            const rate = name === '正常' ? normalRate : overRate;
                            return name + '：' + num + '个，占' + rate + '%'
                        }
                    },
                    // tooltip: {
                    //     formatter: params => {
                    //         if (params.seriesName !== 'mouseoutSeries') {
                    //             return `${params.seriesName}<br/><span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${params.color};"></span>${option.series[params.seriesIndex].pieData.value}`;
                    //         }
                    //     }
                    // },
                    xAxis3D: {
                        min: -1,
                        max: 1
                    },
                    yAxis3D: {
                        min: -1,
                        max: 1
                    },
                    zAxis3D: {
                        min: -1,
                        max: 1
                    },
                    grid3D: {
                        show: false,
                        boxHeight: 10,
                        bottom: 10,
                        viewControl: {//3d效果可以放大、旋转等，参考官方配置
                            alpha: 45,
                            distance: 250,
                            rotateSensitivity: 0,
                            zoomSensitivity: 0,
                            panSensitivity: 0,
                            autoRotate: true
                        }
                    },
                    series: series
                };
                return option;
            }

            // 传入数据生成 option
            var myChart = echarts.init(document.getElementById('overCntPieChart'), 'darkTheme');
            mychartsList.push(myChart);
            var option = getPie3D([{
                name: '正常',
                value: normalCnt,
                itemStyle: {
                    opacity: .8,
                    color: 'rgba(0, 149, 227, 1)'
                }
            },{
                name: '超标',
                value: overCnt,
                itemStyle: {
                    opacity: .8,
                    color: 'rgba(255,36,39,1)'
                }
            }], 0.5);
            myChart.setOption(option);

            myChart.off().on('click' , function (params) {
                let areaList = []; let meterList = [];
                overList.forEach(function (item) {
                    areaList.push(item.areaId);
                    meterList.push(item.meterCode);
                });
                locals.set('report', {
                    area: areaList,
                    deviceTypeCode: devType,
                    repType: "2",
                    meter: meterList,
                    dateObj: {
                        2: util.toDateString(new Date(), 'yyyy-MM')
                    }
                });

                // 当点击超标，并且有超标仪表时，打开弹窗
                if(params.seriesName === '超标' && meterList.length > 0){
                    // console.log('layer.open');
                    layer.open({
                        type: 2,
                        title: '&nbsp;',
                        closeBtn: 1,
                        shade: 0,
                        anim: 0,
                        area: ['50%', '50%'],
                        maxmin: true,
                        content: ['/report/index.do', 'no'],
                        success: function(layero, index) {
                            let body = layer.getChildFrame('body', index);
                            body.find('.layui-header').addClass('layui-hide');
                            body.find('.layui-side').addClass('layui-hide');
                            body.find('.layui-body').css({top: 0, left: 0});
                            body.find('.layui-body').addClass('iframe-layer');
                        }
                    });
                }
                return false
            })
        }

        // 原2D饼图
        function overCntPieChart(overDataArray,total) {
            const border = '';
            var data = [], color = ['rgba(51, 152, 219, .8)', 'rgba(253, 0, 3, .8)'];
            for (let i = 0; i < overDataArray.length; i++) {
                data.push({
                    value: overDataArray[i].value,
                    name: overDataArray[i].name,
                    itemStyle: {
                        normal: {
                            borderWidth: 8,
                            shadowBlur: 5,
                            borderColor: color[i],
                            shadowColor: color[i]
                        }
                    }
                }, {
                    value: overDataArray[0].value / 10,
                    name: '',
                    itemStyle: {
                        normal: {
                            label: {
                                show: false
                            },
                            labelLine: {
                                show: false
                            },
                            color: 'rgba(0, 0, 0, 0)',
                            borderColor: 'rgba(0, 0, 0, 0)',
                            borderWidth: 0
                        }
                    }
                });
            }
            var myChart = echarts.init(document.getElementById('overCntPieChart'), 'darkTheme');
            mychartsList.push(myChart);
            var option = {
                color: color,
                title: {
                    text: '本月总量超标'+devTypeObj[devType].name+'表占比',
                    x: 'center',
                    y: 10,
                    textStyle: {
                        fontSize: 18,
                        fontWeight: 'normal'
                    }
                },
                legend: {
                    orient: 'vertical',
                    icon: 'none',
                    selectedMode: false,
                    top: 'center',
                    right: 'center',
                    data: overDataArray.map(it => it.name),
                    textStyle: {
                        color: '#fff',
                        fontSize: 16,
                        textAlign: 'center'
                    },
                    formatter: function(name) {
                        // const str = name === '正常' ? decimalNum(overDataArray[0].value / total * 100): decimalNum(overDataArray[1].value / total * 100)
                        const str = name === '正常' ? overDataArray[0].value / total * 100: overDataArray[1].value / total * 100;
                        return name + '：' + str + '%'
                    }
                },
                tooltip: {
                    show: false
                },
                graphic: {
                    elements: [{
                        type: 'image',
                        z: 1,
                        style: {
                            image: border,
                            width: 200,
                            height: 200
                        },
                        left: 'center',
                        top: 'center',
                        position: [100, 100]
                    }

                    ]
                },
                series: [{
                    name: '',
                    type: 'pie',
                    clockWise: false,
                    radius: ['55%', '60%'],
                    center: ['50%', '50%'],
                    hoverAnimation: false,
                    itemStyle: {
                        normal: {
                            label: {
                                show: true,
                                fontSize: 16,
                                textShadowColor: 'rgba(255, 255, 255, .6)',
                                textShadowBlur: 1,
                                formatter(params) {
                                    return params.name ? params.name + '\n' + params.value + '个' : '';
                                }
                            },
                            labelLine: {
                                width: 4,
                                length: 10,
                                length2: 15,
                                show: true,
                                color: '#00ffff'
                            }
                        }
                    },
                    data
                }]
            };
            myChart.setOption(option);
            window.addEventListener("resize", function () {
                myChart.resize();
            });
        }

        // 渲染超标水表表格
        function overCntTable(datalist) {
            var h = $('.list').height() - 50;
            table.render({
                elem: '#overTable'
                ,height: h
                ,data: datalist
                // ,skin:'nob'
                ,size:'sm'
                ,cols: [[
                    {field: 'anotherName', title: devTypeObj[devType].name + '表位置', width: 150}
                    ,{field: 'superWater', title: '超出量('+devTypeObj[devType].unit+')', width: 93, templet: '<div><span style="color: red;">{{ d.superWater }}</span></div>'}
                    ,{field: 'superRate', title: '超标率'}
                ]],
                limit: datalist.length
            })
        }

        // 本月日用水量趋势 折线图
        function monthDaysTrendLine(dataList) {
            var xAxisArray = [];
            var seriesArray = [];
            var standardUsage = [];
            if (dataList != null && dataList.length > 0) {
                for (var i = 0; i < dataList.length; i++) {
                    xAxisArray.push(dataList[i].day);
                    seriesArray.push(dataList[i].intervalQuantity); // dataList[i].intervalQuantity
                    standardUsage.push(dataList[i].standard);
                }
            }
            var max1 = Math.max(...seriesArray);
            var max2 = Math.max(...standardUsage);
            var ymax = max1 > max2 ? Math.ceil(max1+10) : Math.ceil(max2+10);

            var myChart = echarts.init(document.getElementById('monthDaysTrend'), 'darkTheme');
            mychartsList.push(myChart);
            var option = {
                color:['rgba(51, 152, 219,1)','rgba(253,47,60,0.9)'],
                title: {
                    text: '本月日用'+devTypeObj[devType].name+'量趋势',
                    x: 'center',
                    y: 10,
                    textStyle: {
                        fontSize: 18,
                        fontWeight: 'normal'
                    }
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        lineStyle: {
                            color: {
                                type: 'linear',
                                x: 0,
                                y: 0,
                                x2: 0,
                                y2: 1,
                                colorStops: [{
                                    offset: 0,
                                    color: 'rgba(0, 255, 233,0)'
                                }, {
                                    offset: 0.5,
                                    color: 'rgba(255, 255, 255,1)',
                                }, {
                                    offset: 1,
                                    color: 'rgba(0, 255, 233,0)'
                                }],
                                global: false
                            }
                        },
                    },
                    backgroundColor: 'rgba(18,37,79,.5)',
                    textStyle: {
                        color: '#fff'
                    },
                    padding: [10, 10],
                    extraCssText: 'border:1px solid #3398DB ;box-shadow: 1px 0 2px 0 rgba(163,163,163,0.5)'
                },
                legend: {  //图示
                    orient: 'vertical',
                    right: 10,
                    top: 10,
                    bottom: 20,
                    data: ['用'+devTypeObj[devType].name+'量', '标准量']
                },
                xAxis: {
                    name: '日期',
                    type: 'category',
                    boundaryGap: false,
                    splitLine: {
                        show: false
                    },
                    data: xAxisArray.map(function (str) {
                        return str.substring(5);
                    })
                },
                yAxis: {
                    name: devTypeObj[devType].unit,
                    type: 'value',
                    max: ymax
                },
                series: [{
                    name: '用'+devTypeObj[devType].name+'量',
                    data: seriesArray,//[820, 932, 901, 934, 1290, 1330, 1320],
                    type: 'line',
                    symbol: 'circle', //设定为实心点
                    symbolSize: 1,  //点的大小
                    lineStyle: {
                        width: 2,
                        normal: {
                            color: "#3398DB",
                            shadowColor: 'rgba(0, 0, 0, .3)',
                            shadowBlur: 0,
                            shadowOffsetY: 2,
                            shadowOffsetX: 2,
                        },
                    },
                    areaStyle: {
                        color: {
                            type: 'linear', x: 0, y: 0, x2: 0, y2: 1,
                            colorStops: [{
                                offset: 0, color: 'rgba(51, 152, 219, .6)' // 0% 处的颜色
                            }, {
                                offset: 1, color: 'rgba(51, 152, 219, 0)' // 100% 处的颜色
                            }],
                            global: false // 缺省为 false
                        }
                    },
                    emphasis: {
                        label: {
                            show: true, // 显示数值
                            position: 'top',
                            fontSize: 16,
                            color: '#3398DB',
                            fontWeight: 'bold'
                        },
                        itemStyle: {
                            color: "#00b3f4",
                            borderColor: "#fff",
                            borderWidth: 3,
                            shadowColor: 'rgba(0, 0, 0, .3)',
                            shadowBlur: 0,
                            shadowOffsetY: 2,
                            shadowOffsetX: 2,
                        },
                    },
                    markPoint: {
                        label: {
                            normal: {
                                textStyle: {
                                    color: '#fff'
                                }
                            }
                        },
                        data: [{
                            type: 'max',
                            name: '最大值',

                        }, {
                            type: 'min',
                            name: '最小值'
                        }]
                    },
                },
                    {
                        name: '标准量',
                        data: standardUsage,//[820, 932, 901, 934, 1290, 1330, 1320],
                        type: 'line',
                        symbol: 'circle', //设定为实心点
                        symbolSize: 1,  //点的大小
                        areaStyle: {
                            color: {
                                type: 'linear', x: 0, y: 0, x2: 0, y2: 1,
                                colorStops: [{
                                    offset: 0, color: 'rgba(253,47,60, 0.15)' // 0% 处的颜色
                                }, {
                                    offset: 1, color: 'rgba(253,47,60, 0)' // 100% 处的颜色
                                }],
                                global: false // 缺省为 false
                            }
                        },
                        lineStyle: {
                            width: 2,
                            normal: {
                                shadowColor: 'rgba(0, 0, 0, .3)',
                                shadowBlur: 0,
                                shadowOffsetY: 2,
                                shadowOffsetX: 2,
                            },
                        },
                        emphasis: {
                            label: {
                                show: true, // 显示数值
                                position: 'top',
                                fontSize: 16,
                                color: '#ccc',
                                fontWeight: 'bold'
                            },
                            itemStyle: {
                                color: "rgba(255, 255, 255, .3)",
                                borderColor: "rgba(255, 255, 255, .5)",
                                borderWidth: 3,
                                shadowColor: 'rgba(0, 0, 0, .3)',
                                shadowBlur: 0,
                                shadowOffsetY: 2,
                                shadowOffsetX: 2,
                            },
                        },
                    }]
            };
            myChart.setOption(option);
            window.addEventListener("resize", function () {
                myChart.resize();
            });

            var app = {
                currentIndex: -1,
            };
            clearInterval(toolTipObj.timer1);
            toolTipObj.timer1 = null;
            toolTipObj.timer1 = setInterval(function () {
                var dataLen = option.series[0].data.length;

                // 取消之前高亮的图形
                myChart.dispatchAction({
                    type: 'downplay',
                    seriesIndex: 0,
                    dataIndex: app.currentIndex
                });
                app.currentIndex = (app.currentIndex + 1) % dataLen;
                //console.log(app.currentIndex);
                // 高亮当前图形
                myChart.dispatchAction({
                    type: 'highlight',
                    seriesIndex: 0,
                    dataIndex: app.currentIndex,
                });
                // 显示 tooltip
                myChart.dispatchAction({
                    type: 'showTip',
                    seriesIndex: 0,
                    dataIndex: app.currentIndex
                });


            }, 1500);
        }

        // 渲染区域选择
        function renderAreaSel(AreaList){
            $('#areaSel').empty();
            var opts = '';
            for (let i = 0; i < AreaList.length; i++) {
                opts += '<option value="' + AreaList[i].areaId + '">' + AreaList[i].areaName + '</option>'
            }
            $('#areaSel').append(opts);
            formSelects.render('areaMenu');
            formSelects.btns('areaMenu',[]);
            formSelects.value('areaMenu', 'val');
            areaArr.length = 0;
            localParam = locals.get(pageName);
            if(localParam){
                formSelects.value('areaMenu', localParam.area);
                areaArr = localParam.area.map(function(val){
                    return val;
                });
            }else{
                areaArr = AreaList.map(function (item) {
                    return item.areaId
                });
                formSelects.value('areaMenu', areaArr);
                locals.set(pageName, {area: areaArr, type: devType});
            }
        }

        // 本月设备累计用量
        function curMonthCount(areaArr, monitorMeters) {
            // 过滤出所选区域的所有水表
            var list = [];
            monitorMeters.forEach(function(item){
                areaArr.forEach(function(val){
                    if(item.areaId == val){
                        list.push(item);
                    }
                });
            });

            var xAxisArray = []; // x轴：水表名称
            var seriesArray = []; // y轴：用水量
            var monthTotal = []; //标准值
            if (list != null && list.length > 0) {
                for (var i = 0; i < list.length; i++) {
                    xAxisArray.push(list[i].anotherName);
                    seriesArray.push(list[i].intervalQuantity);
                    monthTotal.push(list[i].monthTotal == undefined ? 0 : list[i].monthTotal);
                }
            }

            var barWidth = xAxisArray.length <= 6 ? 30 : 20;
            var bottomArr = [];
            for (var i = 0; i < seriesArray.length; i++) {
                bottomArr.push(1)
            }
            if (myChart != null && myChart != "" && myChart != undefined) { //判断是否已经存在myChart实例，有则销毁
                myChart.dispose();
            }
            var myChart = echarts.init(document.getElementById('grandTotalBox'), 'darkTheme');
            mychartsList.push(myChart);
            myChart.clear();
            var grandTotaloption = {
                // color: ['rgba(51, 152, 219, .8)', 'rgba(153, 153, 153, .8)'],
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow'
                    },
                    formatter: function (v) {
                        // console.log(v)
                        var s1 = v[2].marker + v[2].seriesName + ': ' + v[2].value; //用量
                        // var s2 = v[5].marker + v[5].seriesName + ': ' + v[5].value; //标准
                        return v[0].name + "<br>" + s1
                    },
                    backgroundColor: 'rgba(18,37,79,.5)',
                    textStyle: {
                        color: '#fff'
                    },
                    padding: [10, 10],
                    extraCssText: 'border:1px solid #3398DB ;box-shadow: 1px 0 2px 0 rgba(163,163,163,0.5)'
                },
                legend: {  //图示
                    orient: 'vertical',
                    selectedMode: false, // 禁用图例点击事件
                    right: 10,
                    top: 10,
                    bottom: 20,
                    icon: 'roundRect',
                    data: ['用'+devTypeObj[devType].name+'量', '月累计标准量']
                },
                dataZoom: [{
                    show: true,
                    height: 15,
                    xAxisIndex: [0],
                    bottom: 10,
                    startValue: 0,
                    endValue: 10,
                    // brushSelect: false,
                    handleSize: '100%',
                    handleStyle: {
                        color: "#5B3AAE",
                    },
                    textStyle:{
                        color:"rgba(204,187,225,0.5)",
                    },
                    fillerColor:"rgba(67,55,160,0.4)",
                    borderColor: "rgba(204,187,225,0.5)",
                }, {
                    type: "inside",
                    show: true,
                    // brushSelect: false,
                    height: 15,
                    startValue: 0,
                    endValue: 10
                }],
                grid: {
                    bottom: '25%'
                },
                xAxis: {
                    // name: '设备',
                    //nameRotate:-25,
                    type: 'category',
                    data: xAxisArray.map(function (str) {
                        return  str.slice(0,5) +'\n' +str.slice(5);
                    }),
                    axisPointer: {
                        type: 'shadow'
                    },
                    splitLine: {
                        show: false
                    },
                },
                yAxis: [
                    {
                        type: 'value',
                        name: devTypeObj[devType].unit
                    }
                ],
                series:[
                    { //  柱身
                        // name: '用水量',
                        data: seriesArray,
                        type: "bar",
                        barMaxWidth: "auto",
                        barWidth: barWidth,
                        itemStyle: style[0],
                    }, { // 底
                        data: bottomArr,
                        type: "pictorialBar",
                        barMaxWidth: barWidth,
                        symbol: "diamond",
                        symbolOffset: ['-50%', "50%"],
                        // symbolOffset: [0, "50%"],
                        symbolSize: [barWidth, 15],
                        itemStyle: style[0],
                    }, { // 顶
                        name: '用'+devTypeObj[devType].name+'量',
                        data: seriesArray,
                        type: "pictorialBar",
                        barMaxWidth: barWidth,
                        symbolPosition: "end",
                        symbol: "diamond",
                        symbolOffset: ['-50%', "-50%"],
                        // symbolOffset: [0, "-50%"],
                        symbolSize: [barWidth, 12],
                        zlevel: 2,
                        itemStyle: {
                            color: '#0095e3'
                        },
                        emphasis: {
                            label: {
                                show: true, // 显示数值
                                position: 'top',
                                fontSize: 16,
                                color: '#3398DB',
                                fontWeight: 'bold'
                            },
                            itemStyle: {
                                color: "#00b3f4",
                                borderColor: "#fff",
                                borderWidth: 1,
                                shadowColor: 'rgba(0, 0, 0, .3)',
                                shadowBlur: 0,
                                shadowOffsetY: 2,
                                shadowOffsetX: 2,
                            },
                        },
                    },
                    //  各表月累计
                    {   // 柱身
                        data: monthTotal,
                        type: "bar",
                        barMaxWidth: barWidth,
                        barGap: 0,
                        barWidth: barWidth,
                        itemStyle: style[1]
                    },
                    {   // 底面
                        data: bottomArr,
                        type: "pictorialBar",
                        barMaxWidth: barWidth,
                        symbol: "diamond",
                        symbolOffset: ['50%', "50%"],
                        symbolSize: [barWidth, 15],
                        itemStyle: style[1],
                    },
                    {
                        // 顶面
                        name: '月累计标准量',
                        data: monthTotal,
                        type: "pictorialBar",
                        barMaxWidth: barWidth,
                        symbolPosition: "end",
                        symbol: "diamond",
                        symbolOffset: ['50%', "-50%"],
                        symbolSize: [barWidth, 12],
                        itemStyle: {
                            color:'#666'
                        },
                        zlevel: 2,
                        emphasis: {
                            label: {
                                show: true, // 显示数值
                                position: 'top',
                                fontSize: 16,
                                color: '#ccc',
                                fontWeight: 'bold'
                            },
                            itemStyle: {
                                color: "#ccc",
                                borderColor: "rgba(255, 255, 255, .5)",
                                borderWidth: 1,
                                shadowColor: 'rgba(0, 0, 0, .3)',
                                shadowBlur: 0,
                                shadowOffsetY: 2,
                                shadowOffsetX: 2,
                            },
                        },
                    }
                ]
            };
            myChart.setOption(grandTotaloption);
            window.addEventListener("resize", function () {
                myChart.resize();
            });

            let app = {
                currentIndex: -1,
            };
            clearInterval(toolTipObj.timer2);
            toolTipObj.timer2 = null;
            toolTipObj.timer2 = setInterval(function () {
                let dataLen = grandTotaloption.series[0].data.length;

                // 取消之前高亮的图形
                myChart.dispatchAction({
                    type: 'downplay',
                    seriesIndex: 0,
                    dataIndex: app.currentIndex
                });
                app.currentIndex = (app.currentIndex + 1) % dataLen;
                //console.log(app.currentIndex);
                // 高亮当前图形
                myChart.dispatchAction({
                    type: 'highlight',
                    seriesIndex: 0,
                    dataIndex: app.currentIndex,
                });
                // 显示 tooltip
                myChart.dispatchAction({
                    type: 'showTip',
                    seriesIndex: 0,
                    dataIndex: app.currentIndex
                });
            }, 1500);
        }

        // 每月用水总量 -- 数据请求
        function bindMonthTotal() {
            $.ajax({
                type: "post",
                url: ctx + "/integrate/getMeterGyMonth.do",
                data: JSON.stringify({deviceTypeCode: devType}),
                contentType: "application/json",
                async: true,
                cache: false,
                dataType: "json",
                success: function (res) {
                    if (res.code == "000000") {
                        var list = res.data;
                        var xAxisArray = [];
                        var seriesArray = [];
                        var monthMeterStandar = [];
                        var economy = [];

                        // var xAxisArray = ['2019-10','2019-11','2019-12','2020-01'];
                        // var seriesArray = [1500, 2300, 2240, 2180];
                        // var monthMeterStandar = [2200, 2820, 2910, 2340];
                        // var economy = [0.15,0.22,0.16,0.11];

                        //当月用水总量
                        if (list != null && list.length > 0) {
                            for (var i = 0; i < list.length; i++) {
                                xAxisArray.push(list[i].uploadDateStr);
                                seriesArray.push(list[i].intervalQuantity);
                                monthMeterStandar.push(list[i].monthMeterStandar);
                                economy.push(list[i].economy);
                            }
                        }
                        everyMonthTotal(xAxisArray, seriesArray, monthMeterStandar, economy);

                    } else {
                        layer.alert("系统异常，" + res.message);
                    }
                }, error: function (e) {
                    layer.alert("系统异常，请稍后再试");
                }, complete: function () {
                    //layer.closeAll('loading');
                }
            });
        }

        // 每月用水总量统计 -- 柱图
        function everyMonthTotal(xAxisArray, seriesArray, monthMeterStandar, economy) {
            var barWidth = xAxisArray.length <= 6 ? 30 : xAxisArray.length <= 12 ? 20 : 12;
            var bottomArr = [];
            for (var i = 0; i < seriesArray.length; i++) {
                bottomArr.push(1)
            }
            let dataZoomEnd = xAxisArray.length <= 6 ? 100 : 60;
            var myChart = echarts.init(document.getElementById('monthTotal'), 'darkTheme');
            mychartsList.push(myChart);
            var option = {
                // color: ['rgba(51, 152, 219, .8)', 'rgba(153, 153, 153, 0.8)'],
                title: {
                    text: '月用'+devTypeObj[devType].name+'总量统计',
                    x: 'center',
                    y: 10,
                    textStyle: {
                        fontSize: 18,
                        fontWeight: 'normal'
                    }
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {            // 坐标轴指示器，坐标轴触发有效
                        type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
                    },
                    formatter: function (v) {
                        var s1 = v[2].marker + v[2].seriesName + ': ' + v[2].value; //用量
                        var s2 = v[5].marker + v[5].seriesName + ': ' + v[5].value; //标准
                        var s3 = v[6].marker + v[6].seriesName + ': ' + v[6].value * 100 + '%'; //节约率
                        return v[0].name + "<br>" + s1 + '<br>' + s2 + '<br>' + s3
                    },
                    backgroundColor: 'rgba(18,37,79,.5)',
                    textStyle: {
                        color: '#fff'
                    },
                    padding: [10, 10],
                    extraCssText: 'border:1px solid #3398DB ;box-shadow: 1px 0 2px 0 rgba(163,163,163,0.5)'
                },
                legend: {  //图示
                    orient: 'vertical',
                    selectedMode: false, // 禁用图例点击事件
                    right: 10,
                    top: 10,
                    bottom: 20,
                    icon: 'roundRect',
                    data: ['用'+devTypeObj[devType].name+'量', '标准量']
                },
                xAxis: {
                    name: '日期',
                    type: 'category',
                    axisPointer: {
                        type: 'shadow'
                    },
                    splitLine: {
                        show: false
                    },
                    data: xAxisArray
                },
                yAxis: [{
                    name: devTypeObj[devType].unit,
                    type: 'value'
                }
                ],
                dataZoom: [{
                    show: true,
                    height: 15,
                    xAxisIndex: [0],
                    bottom: 20,
                    start: 0,
                    end: dataZoomEnd,
                    handleSize: '100%',
                    handleStyle: {
                        color: "#5B3AAE",
                    },
                    textStyle:{
                        color:"rgba(204,187,225,0.5)",
                    },
                    fillerColor:"rgba(67,55,160,0.4)",
                    borderColor: "rgba(204,187,225,0.5)",
                }, {
                    type: "inside",
                    show: true,
                    height: 15,
                    start: 1,
                    end: dataZoomEnd
                }],
                series: [
                    // 用水量
                    { //  柱身
                        // name: '用水量',
                        data: seriesArray,
                        type: "bar",
                        barMaxWidth: "auto",
                        barWidth: barWidth,
                        itemStyle: style[0],
                    }, { // 底
                        data: bottomArr,
                        type: "pictorialBar",
                        barMaxWidth: barWidth,
                        symbol: "diamond",
                        symbolOffset: ['-50%', "50%"],
                        symbolSize: [barWidth, 15],
                        itemStyle: style[0],
                    }, { // 顶
                        name: '用'+devTypeObj[devType].name+'量',
                        data: seriesArray,
                        type: "pictorialBar",
                        barMaxWidth: barWidth,
                        symbolPosition: "end",
                        symbol: "diamond",
                        symbolOffset: ['-50%', "-50%"],
                        symbolSize: [barWidth, 12],
                        zlevel: 2,
                        itemStyle: {
                            color: '#0095e3'
                        },
                        emphasis: {
                            label: {
                                show: true, // 显示数值
                                position: 'top',
                                fontSize: 16,
                                color: '#3398DB',
                                fontWeight: 'bold'
                            },
                            itemStyle: {
                                color: "#00b3f4",
                                borderColor: "#fff",
                                borderWidth: 1,
                                shadowColor: 'rgba(0, 0, 0, .3)',
                                shadowBlur: 0,
                                shadowOffsetY: 2,
                                shadowOffsetX: 2,
                            },
                        },
                    },
                    //  标准量
                    {   // 柱身

                        data: monthMeterStandar,
                        type: "bar",
                        barMaxWidth: barWidth,
                        barGap: 0,
                        barWidth: barWidth,
                        itemStyle: style[1]
                    },
                    {   // 底面
                        data: bottomArr,
                        type: "pictorialBar",
                        barMaxWidth: barWidth,
                        symbol: "diamond",
                        symbolOffset: ['50%', "50%"],
                        symbolSize: [barWidth, 15],
                        itemStyle: style[1],
                    },
                    {
                        // 顶面
                        name: '标准量',
                        data: monthMeterStandar,
                        type: "pictorialBar",
                        barMaxWidth: barWidth,
                        symbolPosition: "end",
                        symbol: "diamond",
                        symbolOffset: ['50%', "-50%"],
                        symbolSize: [barWidth, 12],
                        itemStyle: {
                            color:'#666'
                        },
                        zlevel: 2,
                        emphasis: {
                            label: {
                                show: true, // 显示数值
                                position: 'top',
                                fontSize: 16,
                                color: '#ccc',
                                fontWeight: 'bold'
                            },
                            itemStyle: {
                                color: "#ccc",
                                borderColor: "rgba(255, 255, 255, .5)",
                                borderWidth: 1,
                                shadowColor: 'rgba(0, 0, 0, .3)',
                                shadowBlur: 0,
                                shadowOffsetY: 2,
                                shadowOffsetX: 2,
                            },
                        },
                    },
                    {
                        name: '节约率',
                        type: 'line',
                        symbolSize: 0,
                        color: 'transparent',
                        data: economy
                    }
                ]
            };
            myChart.setOption(option);

            var app = {
                currentIndex: -1,
            };
            clearInterval(toolTipObj.timer3);
            toolTipObj.timer3 = null;
            toolTipObj.timer3 = setInterval(function () {
                var dataLen = option.series[0].data.length;

                // 取消之前高亮的图形
                myChart.dispatchAction({
                    type: 'downplay',
                    seriesIndex: 0,
                    dataIndex: app.currentIndex
                });
                app.currentIndex = (app.currentIndex + 1) % dataLen;
                //console.log(app.currentIndex);
                // 高亮当前图形
                myChart.dispatchAction({
                    type: 'highlight',
                    seriesIndex: 0,
                    dataIndex: app.currentIndex,
                });
                // 显示 tooltip
                myChart.dispatchAction({
                    type: 'showTip',
                    seriesIndex: 0,
                    dataIndex: app.currentIndex
                });
            }, 1500);


            window.addEventListener("resize", function () {
                myChart.resize();
            });
        }

        // 监听区域多选
        formSelects.on('areaMenu', function(id, vals, val, isAdd, isDisabled){
            areaArr.length = 0; // 清空areaArr
            vals.forEach(function(item){
                areaArr.push(item.value);
            });
            locals.set(pageName,{area: areaArr, type: devType});
            curMonthCount(areaArr, grandTotalData);
        }, true);
        // formSelects.maxTips('areaMenu', function(id, vals, val, max){
        //     layer.alert("区域最多选" + max + '项');
        // });

        // 页面刷新
        function refreshPage(){
            if (counter == 12) {  // 刷到12次就重载页面 即2h
                window.location.reload();
            }
            if (pagetimer) {
                clearTimeout(pagetimer);
                pagetimer = null;
            }
            pagetimer = setTimeout(() => {
                init();
                refreshPage();
                counter++;
            }, interval);
        }
        refreshPage();

        //打印
        $(".pdfBtn").click(function () {
            $(this).attr("disabled", "disabled");
            $(this).css("display", "none");
            html2canvas($(".printBox"), {
                // 设置背景色
                background :'#12254f',
                // 渲染完成时调用，获得 canvas
                onrendered: function (canvas) {
                    //返回图片dataURL，参数：图片格式和清晰度(0-1)
                    var pageData = canvas.toDataURL("image/png", 1.0);
                    //landscape横向,a4[595.28,841.89]
                    var pdf = new jsPDF('landscape', 'pt', 'a4');
                    //addImage后两个参数控制添加图片的尺寸，此处将页面高度按照a4纸宽高比列进行压缩
                    pdf.addImage(pageData, 'png', 0, 0, 841.89, 841.89 / canvas.width * canvas.height);
                    // console.log(pdf);
                    pdf.save('综合页面.pdf');
                    $(".pdfBtn").css("display", "block");
                    $(".pdfBtn").removeAttr("disabled");
                }
            });
        })

    })
});
